package com.wufun.overseas.main.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.papa91.arc.EmuActivity;
import com.papa91.arcapp.AppConfig;
import com.wufun.baselibrary.base.BaseAppCompatActivity;
import com.wufun.baselibrary.download.CommonDownloadFactory;
import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.utils.AppInfoUtil;
import com.wufun.baselibrary.utils.LogUtils;
import com.wufun.overseas.R;
import com.wufun.overseas.common.TabTypeInterface;
import com.wufun.overseas.dot.DotConfig;
import com.wufun.overseas.dot.DotRequestManager;
import com.wufun.overseas.dot.DotService;
import com.wufun.overseas.main.activity.MainActivity;
import com.wufun.overseas.models.db.DotRequestTable;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.models.event.DownloadResultEvent;
import com.wufun.overseas.tools.DownloadManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by tangbingliang on 17/2/16.
 */

public class MyActivity extends BaseAppCompatActivity implements CommonDownloadFactory.DownloadListener {

    private LinearLayout rootContentLl;
    private ImageView baseLineIv;
    private ImageView barTitleIv;
    private TextView barTitleTx;
    private RelativeLayout barTitleRl;
    private ImageView barBackIv;
    protected LinearLayout barBackLl;
    private TextView barRightTx;
    private ImageView barRightIv;
    private RelativeLayout barRightRl;
    protected RelativeLayout rootBarRl;
    private LinearLayout baseTopLl;

    private Display display;

    protected Context mContext;
    protected Activity mAty;
    protected CommonDownloadFactory factory;

    @Subscribe
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_mybase);

        mAty = this;
        mContext = this;
        display = getWindowManager().getDefaultDisplay();
        factory = CommonDownloadFactory.get();
        factory.setListener(this);

        EventBus.getDefault().register(mContext);

        if (mAty instanceof MainActivity) {
            DotRequestTable temp = new DotRequestTable(null
                    , AppInfoUtil.getIMEI(mContext)
                    , AppInfoUtil.getAppMac(mContext)
                    , ""
                    , mContext.getResources().getString(R.string.app_name)
                    , AppInfoUtil.getAppVersionName(mContext)
                    , ""
                    , System.currentTimeMillis()
                    , false
                    , 0, DotConfig.EVENT_STARTAPP);
            DotRequestManager.getInstance().insertDownload(temp);
        }
    }

    @Override
    public void setContentView(int layoutResID) {

        //标题栏最外层
        rootBarRl = (RelativeLayout) findViewById(R.id.root_bar_rl);
        //标题栏标题外层
        barTitleRl = (RelativeLayout) findViewById(R.id.bar_title_rl);

        //标题栏标题文字控件
        barTitleTx = (TextView) findViewById(R.id.bar_title_tx);
        //标题栏标题图片控件
        barTitleIv = (ImageView) findViewById(R.id.bar_title_iv);

        //标题栏返回外层
        barBackLl = (LinearLayout) findViewById(R.id.bar_back_ll);
        barBackLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //标题栏返回图片控件
        barBackIv = (ImageView) findViewById(R.id.bar_back_iv);
        //标题栏分割点
        baseLineIv = (ImageView) findViewById(R.id.base_line_iv);

        //标题栏右边文字控件
        barRightTx = (TextView) findViewById(R.id.bar_right_tx);
        //标题栏右边图片控件
        barRightIv = (ImageView) findViewById(R.id.bar_right_iv);
        //标题栏右边外层
        barRightRl = (RelativeLayout) findViewById(R.id.bar_right_rl);

        //基类内容显示区域
        rootContentLl = (LinearLayout) findViewById(R.id.root_content_ll);

        //子类布局
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(layoutResID, null);
        v.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        rootContentLl.addView(v);
    }

    /********************** 基类生命周期方法***********************/

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
//        if (mShouldLogin) {
//            if (!isLogin()) {
//                //需要登陆状态，跳转到登陆界面
//                startActivity(LoginActivity.createIntent(this, getIntent()));
//            }
//        }
    }

    @Override
    protected void onDestroy() {
        factory.removeListener(this);
        EventBus.getDefault().unregister(mContext);
        super.onDestroy();
    }

    /*********************基类Title控件操作***********************/

    public RelativeLayout getRootBarRl() {
        return rootBarRl;
    }

    public LinearLayout getRootContentLl() {
        return rootContentLl;
    }

    /**
     * 返回按钮
     */
    protected LinearLayout getBarBackLl() {
        return barBackLl;
    }

    /**
     * 影藏头部
     */
    protected void hideTitleBar() {
        if (rootBarRl != null) {
            rootBarRl.setVisibility(View.GONE);
            baseLineIv.setVisibility(View.GONE);
        }
    }

    /**
     * 显示头部
     */
    protected void showTitleBar() {
        if (rootBarRl != null) {
            rootBarRl.setVisibility(View.VISIBLE);
            baseLineIv.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示标题文字，隐藏bar图片
     */
    public TextView setBarTitleTx(String str) {
        barTitleTx.setVisibility(View.VISIBLE);
        barTitleIv.setVisibility(View.GONE);
        barTitleTx.setText(str);
        return barTitleTx;
    }

    /**
     * 显示标题文字，隐藏bar图片
     */
    public TextView setBarTitleTx(int id) {
        barTitleTx.setVisibility(View.VISIBLE);
        barTitleIv.setVisibility(View.GONE);
        barTitleTx.setText(getResources().getString(id));
        return barTitleTx;
    }

    /**
     * 显示标题图片，隐藏标题文字
     */
    public ImageView setBarTitleIv(int id) {
        barTitleTx.setVisibility(View.GONE);
        barTitleIv.setVisibility(View.VISIBLE);
        barTitleIv.setImageResource(id);
        return barTitleIv;
    }

    /**
     * 显示标题右边文字，隐藏标题右边图片
     */
    protected ImageView setBarRightIv() {
        barRightIv.setVisibility(View.VISIBLE);
        barRightTx.setVisibility(View.GONE);
        return barRightIv;
    }

    /**
     * 显示标题右边文字，隐藏标题右边图片
     */
    protected ImageView setBarRightIv(int id) {
        barRightIv.setVisibility(View.VISIBLE);
        barRightTx.setVisibility(View.GONE);
        barRightIv.setImageResource(id);
        return barRightIv;
    }

    /**
     * 显示标题右边
     */
    protected RelativeLayout getBarRightRl() {
        barRightRl.setVisibility(View.VISIBLE);
        return barRightRl;
    }

    /**
     * 显示标题右边图片，隐藏标题右边文字
     */
    protected TextView setBarRightTx(String txt) {
        barRightTx.setVisibility(View.VISIBLE);
        barRightIv.setVisibility(View.GONE);
        barRightTx.setText(txt);
        return barRightTx;
    }

    /**
     * 显示标题右边图片，隐藏标题右边文字
     */
    protected TextView setBarRightTx(int id) {
        barRightTx.setVisibility(View.VISIBLE);
        barRightIv.setVisibility(View.GONE);
        barRightTx.setText(getResources().getString(id));
        return barRightTx;
    }

    /********************** 基类帮助方法***********************/

    public boolean isDownOk(String url) {
        boolean temp = false;
        if (DownloadManager.getInstance().isExist(url)
                && DownloadManager.getInstance().isFinish(url)) {
            temp = true;
            DownLoadModel downLoadModel = DownloadManager.getInstance().getDownloadByUrl(url);
            File file = new File(downLoadModel.getDownloadDir()+downLoadModel.getGameZipName().replace(".zip",""));
        }
        return temp;
    }

    /**
     * gameName 游戏名
     * url 下载url
     * img 图片
     * gameSize 下载文件大小
     * */
    public void addDownloadToDB (String gameName, String url, String gameId, String img, String gameSize, String typeStr) {

        String filedir = MyApplication.getMyApplication().getAppRootPath();
        String zipName = url.substring(url.lastIndexOf("/")+1);
        if (zipName.contains("_"))
            zipName = zipName.substring(0, zipName.indexOf("_"))+".zip";

        LogUtils.e("tbl>>>>>>>>filedir:"+filedir+", zipName:"+zipName);

        DownLoadModel temp = new DownLoadModel(
                url,
                gameId,
                filedir,
                filedir + zipName.replace(".zip",""),
                filedir + zipName,
                0,
                gameSize,
                TabTypeInterface.TYPE_ALL,
                CommonDownloadTask.STATUS_NORMAL,
                0,
                gameName,
                zipName,
                img,
                "0",
                System.currentTimeMillis(),
                typeStr
        );

        DownloadManager mDownloadManager = DownloadManager.getInstance();
        if (!mDownloadManager.isExist(temp.getDownloadUrl())) {
            mDownloadManager.insertDownload(temp);
            try {
                LogUtils.e("tbl>>>>>>>>temp.getDownloadUrl():"+temp.getDownloadUrl());
                LogUtils.e("tbl>>>>>>>>temp.getGameZipName():"+temp.getGameZipName());
                LogUtils.e("tbl>>>>>>>>temp.getDownloadDir():"+temp.getDownloadDir());
                LogUtils.e("tbl>>>>>>>>temp.getGameName():"+temp.getGameName());
                factory.addTask(new CommonDownloadTask(temp.getDownloadUrl()
                        , temp.getGameZipName()
                        , temp.getDownloadDir()
                        , temp.getGameName()));
            } catch (Exception e) {
                showToast(e.getMessage());
            }
        }
    }

    //在注册了的Activity中,声明处理事件的方法
    @Subscribe(threadMode = ThreadMode.MAIN) //第2步:注册一个在后台线程执行的方法,用于接收事件
    public void onUserEvent(DownloadResultEvent eventData) {//参数必须是ClassEvent类型, 否则不会调用此方法
        LogUtils.e(">>>tbl:"+eventData.speed);
        //更新数据库状态
        if (isTopActivity())
            DownloadManager.getInstance().updataDownload(eventData.url
                , eventData.status, eventData.speed);
    }

    public void StartGame(final String url, final String GamePath) {
        File file = new File(GamePath);
//        if (file.exists()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    DownloadManager.getInstance().updataDownload(url, System.currentTimeMillis());
                    String JsonString ="{\"romPath\":\""+ GamePath +"\",\"startMode\":0,\"userID\":\"2000\",\"gameID\":\"509474702\",\"version\":\"2\",\"roomID\":\"10000\",\"serverIP\":\"121.201.0.114\",\"serverPort\":\"5369\",\"porder\":0}";
                    //启动游戏
                    Intent intent=new Intent(mContext, EmuActivity.class);
                    intent.putExtra(AppConfig.KEY_ROM_PATH,GamePath);
                    intent.putExtra(AppConfig.KEY_START_JSON,JsonString);
                    startActivity(intent);
                }
            });
//        } else {
//            showToast(getResources().getString(R.string.toast_not_game_str));
//        }

        DownLoadModel te = DownloadManager.getInstance().getDownloadByUrl(url);
        if (te==null) return;
        String gameId = te.getGameId();
        DotRequestTable temp = new DotRequestTable(null
                , AppInfoUtil.getIMEI(mContext)
                , AppInfoUtil.getAppMac(mContext)
                , ""
                , mContext.getResources().getString(R.string.app_name)
                , AppInfoUtil.getAppVersionName(mContext)
                , gameId
                , System.currentTimeMillis()
                , false
                , 0, DotConfig.EVENT_STARTGAME);
        DotRequestManager.getInstance().insertDownload(temp);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && (mAty instanceof MainActivity)) {// 返回键
            exitBy2Click();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "One more exit program", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            stopService(new Intent(mContext, DotService.class));
            exitApp();
            System.exit(0);
        }
    }

    public int getmHight() {
        return display.getHeight();
    }

    public int getmWidth() {
        return display.getWidth();
    }

    public CommonDownloadFactory getFactory() {
        return factory;
    }

    @Override
    public void onDownloadStart(String url, String gameName) {
        if (isTopActivity())
            showToast(getResources().getString(R.string.download_start_str)+ "\""+ gameName+"\"");
    }

    @Override
    public void onDownloadWait(String url, long size) {

    }

    @Override
    public void onDownloadProgress(String url, int progress, String speed) {
        DownloadManager.getInstance().updataProDownload(url, progress);
    }

    @Override
    public void onDownloadFinish(String url, String gameName) {
        if (isTopActivity())
            showToast("\""+ gameName+"\"" + getResources().getString(R.string.download_su_str));
    }

    @Override
    public void onDownloadError(String url, String gameName) {
        if (isTopActivity())
            showToast("\""+ gameName+"\"" + getResources().getString(R.string.download_fail_str));
    }

    @Override
    public void onDownloadStarZIP(String url, String gameName) {

    }

    @Override
    public void onDownloadZIPProgress(String url, int progress, String speed) {

    }

    @Override
    public void onDownloadZIPError(String url, String gameName) {
        if (isTopActivity())
            showToast("\""+ gameName+"\"" + getResources().getString(R.string.zip_fail_str));
    }

    @Override
    public void onDownloadStop(String url, String gameName) {
        if (isTopActivity())
            showToast(gameName + getResources().getString(R.string.download_stop_str));
    }

    protected boolean isTopActivity() {
        boolean isTop = false;
        ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(mAty.getLocalClassName())) {
            isTop = true;
        }
        return isTop;
    }
}
